const { Sequelize } = require('sequelize');

// 数据库配置
const sequelize = new Sequelize('lingxi_system', 'root', '888mei525', {
  host: 'localhost',
  dialect: 'mysql',
  timezone: '+08:00',
  logging: false
});

async function addOrganizationIdColumn() {
  try {
    await sequelize.authenticate();
    console.log('数据库连接成功');
    
    // 检查是否已经存在organization_id字段
    const [results] = await sequelize.query('DESCRIBE sales_orders');
    const hasOrgId = results.some(row => row.Field === 'organization_id');
    
    if (hasOrgId) {
      console.log('organization_id字段已存在，无需添加');
      await sequelize.close();
      return;
    }
    
    // 添加organization_id字段
    console.log('正在添加organization_id字段...');
    await sequelize.query(`
      ALTER TABLE sales_orders 
      ADD COLUMN organization_id INT NOT NULL DEFAULT 1 AFTER id,
      ADD INDEX idx_sales_orders_organization_id (organization_id)
    `);
    
    console.log('organization_id字段添加成功');
    
    // 验证字段是否添加成功
    const [newResults] = await sequelize.query('DESCRIBE sales_orders');
    const orgIdField = newResults.find(row => row.Field === 'organization_id');
    if (orgIdField) {
      console.log(`字段详情: ${orgIdField.Field} ${orgIdField.Type} ${orgIdField.Null} ${orgIdField.Key} ${orgIdField.Default}`);
    }
    
    await sequelize.close();
  } catch (error) {
    console.error('添加organization_id字段时出错:', error.message);
    if (error.stack) {
      console.error('错误堆栈:', error.stack);
    }
  }
}

addOrganizationIdColumn();